<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addBtn: true,
      }"
      :table-props="{
        selection: true,
        delBtn: true,

        viewBtn: true,
        editBtn: false,
        menuSlot: true,
        menuWidth: 300,
      }"
      :form-props="{
          loading: state.form.loading,
          width: 500,
        }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #rightToolbar></template>

      <template #menuSlot="scope:any">
        <el-tooltip class="box-item" effect="dark" :content="t('business.coupon.action.viewCode')" placement="top">
          <div class="menu-btn">
            <el-button link type="primary" icon="grid" @click="handleItem(scope.row)" />
          </div>
        </el-tooltip>
      </template>

      <template #scope="scope:any">
        <el-tooltip class="box-item" :content="scope.row.stationNames" placement="top-start">
          <DictTag :options="CouponScopeEnum" :value="scope.row.scope" />
        </el-tooltip>
      </template>

      <template #apply="scope:any">
        <DictTag :options="CouponApplyEnum" :value="scope.row.apply" />
      </template>

      <template #accept="scope:any">
        <DictTag :options="CouponAcceptEnum" :value="scope.row.accept" />
      </template>

      <template #state="scope:any">
        <DictTag :options="EnableStatusEnum" :value="scope.row.state" />
      </template>
    </yt-crud>

    <CouponCodeDialog ref="dialogRef" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { list as couponList, remove as couponRemove, save as couponSave, batchRemove as couponBatchRemove } from '@/api/business/coupon'

import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'
import CouponCodeDialog from './modules/code.vue'
import {getStationList} from '@/api/business/station'
const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum, CouponScopeEnum, CouponApplyEnum, CouponAcceptEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum', 'coupon_scope_enum', 'coupon_apply_enum', 'coupon_accept_enum'))

const dialogRef = ref()

const state = reactive({
  form: {
    loading: false,
  },
  page: {
    pageSize: 30,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})

const stations = ref<any[]>([])
const loadStations = () => {
  getStationList({
    pageSize: 9999,
    pageNum: 1,
  })
    .then((res) => {
      stations.value = res.data.rows
    })
    .finally(() => {
      state.loading = false
    })
}
loadStations()

const column = ref<IColumn[]>([
  {
    label: t('business.coupon.name'),
    searchLabelWidth: 120,
    key: 'name',
    search: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.coupon.validator.name') }],
  },
  {
    label: t('business.coupon.scope'),
    key: 'scope',
    colSpan: 22,
    type: 'select',
    componentProps: {
      options: CouponScopeEnum,
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.coupon.validator.scope') }],
    search: true,
    formHide: false,
    slot: true,
    formWatch: (scope) => {
      scope.column.forEach((f: IColumn) => {
        if (f.key === 'stationIds') {
          f.formHide = scope.value === 'All' || scope.value == undefined
        }
      })
      column.value = scope.column
    },
  },
  {
    label: t('business.coupon.stationIds'),
    key: 'stationIds',
    colSpan: 22,
    type: 'i18nSelect',
    componentProps: {
      multiple: true,
      keyAlias: 'id',
      valueAlias: 'name',
      options: stations,
      placeholder: t('business.promotion.placeholder.stationIds')
    },
    rules: [{ required: true, message: t('business.coupon.validator.stationIds') }],
    hide: true,
    search: false,
    formHide: true,
    slot: true,
  },
  {
    label: t('business.coupon.apply'),
    key: 'apply',
    colSpan: 22,
    type: 'select',
    componentProps: {
      options: CouponApplyEnum,
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.coupon.validator.apply') }],
    search: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.coupon.amount'),
    key: 'amount',
    colSpan: 22,
    type: 'number',
    rules: [{ required: true, message: t('business.coupon.validator.amount') }],
    search: false,
    formHide: false,
    slot: false,
    componentProps: {
      precision: 2,
      step: 1,
      min: 1,
      max: 100,
      style: 'width:100%',
    },
  },
  {
    label: t('business.coupon.accept'),
    key: 'accept',
    colSpan: 22,
    type: 'select',
    componentProps: {
      options: CouponAcceptEnum,
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.coupon.validator.accept') }],
    search: false,
    formHide: false,
    slot: true,
    formWatch: (scope) => {
      scope.column.forEach((f: IColumn) => {
        if (f.key === 'acceptIds') {
          f.formHide = scope.value === 'All' || scope.value == undefined
        }
      })
      column.value = scope.column
    },
  },

  {
    label: t('business.coupon.acceptIds'),
    key: 'acceptIds',
    colSpan: 22,
    type: 'selectCustomer',
    componentProps: {
      multiple: true,
    },
    rules: [{ required: true, message: t('business.coupon.validator.acceptIds') }],
    hide: true,
    search: false,
    formHide: true,
    slot: false,

  },
  {
    label: t('business.coupon.enableTime'),
    key: 'enableTime',
    colSpan: 22,
    type: 'date',
    componentProps: {
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.coupon.validator.enableTime') }],
    search: false,
    formHide: true,
    slot: false,
  },
  {
    label: t('business.coupon.expireTime'),
    key: 'expireTime',
    colSpan: 22,
    type: 'date',
    componentProps: {
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.coupon.validator.expireTime') }],
    search: false,
    formHide: false,
    slot: false,
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 5,
    }
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  couponList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.form.loading = true
  couponSave(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.form.loading = false
  })
}

const openBeforeFun = ({ type, data }) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    couponBatchRemove(row.map((m) => m.id)).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  } else {
    couponRemove(row.id).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  }

}

const handleItem = (row: any) => {
  dialogRef.value.openDialog(row)
}
const handleSuccess = () => {}


const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>
